package com.cherry.aop.dao.impl;

import com.cherry.aop.dao.IAccountDao;
import com.cherry.aop.domain.Account;
import com.cherry.aop.util.ConnectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;
    private ConnectionUtil connectionUtils;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }


    public void setConnectionUtils(ConnectionUtil connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    public void updateAccount(Account account) {
        try {
            runner.update(connectionUtils.getThreadConnection(), "update test_account set name=?,money=? where id=?", account.getName(), account.getMoney(), account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Account findAccountByName(String accountName) {
        try {
            List<Account> list = runner.query(connectionUtils.getThreadConnection(), "select * from test_account where name=?", new BeanListHandler<Account>(Account.class), accountName);
            if (list.size() > 1) {
                throw new RuntimeException("查询到重复名字的账户");
            } else {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
